package com.ghsc.ghxc.jsb.ui.my.activity

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.setOnFastChildClickListener
import com.cn.appcore.ext.setOnFastClickListener
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityAddressBinding
import com.ghsc.ghxc.jsb.ext.intentExtras
import com.ghsc.ghxc.jsb.ext.showCustomPopup
import com.ghsc.ghxc.jsb.ui.my.bean.AddressDetailBean
import com.ghsc.ghxc.jsb.view.CenterSelectPopup
import com.ghsc.ghxc.jsb.view.NotDataView
import com.scwang.smart.refresh.layout.api.RefreshLayout
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.my.activity
 * 类名：AddressActivity
 * 创建时间：2024/4/24 20:06
 * 创建人 @author： xiaolin
 * 描述 ：Todo... 地址
 */
class AddressActivity : BaseVMActivity<AddressViewModel, ActivityAddressBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_address
    }

    override fun attachVMClass(): Class<AddressViewModel>? {
        return AddressViewModel::class.java
    }
    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    private val isSelect: Boolean by intentExtras("is_select",false)

    private val shouhuoid: String by intentExtras("id","0")


    private val addressManageAdapter = AddressManageAdapter()
    private var notDataView: View? = null

    override fun initView() {
        binding.bar.topTitle.text="收货地址"
        binding.bar.topLeftView.setSingleClickListener { finish() }
        binding.rvAddress.adapter = addressManageAdapter
        addressManageAdapter.addChildClickViewIds(R.id.llBtnUpdate,R.id.llBtnDelete)
        notDataView = NotDataView.notDataView(this, binding.rvAddress, binding.refreshLayout,"暂无数据")
        initRefreshLayout()
        getListData()

        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe{ rxBusBean ->
                if (rxBusBean.id == CustKey.REFRESH_ADDRESS && rxBusBean.sign == CustKey.REFRESH_ADDRESS) {
                    getListData()
                }
            }
    }

    override fun initClickListener() {
        super.initClickListener()
        binding.stvCreateAddress.setSingleClickListener {
            startKtxActivity<EditAddressActivity>()
        }
        addressManageAdapter.setOnFastClickListener { data, position ->
//            val bean = addressManageAdapter.data[position]
//            var bundle =Bundle()
//            bundle.putSerializable("addressBean",bean)
//            startActivity(EditAddressActivity().javaClass,bundle)



            val bean = addressManageAdapter.data[position]
            if (isSelect){
                val ivSelect = addressManageAdapter.getViewByPosition(position,R.id.ivSelect) as ImageView?
                ivSelect?.run {
                    ivSelect.isSelected = true
                    addressManageAdapter.notifyItemChanged(position)
                }
                lifecycleScope.launch{
                    delay(1000)
                }
                RxBus.getDefault().post(RxBusBean(CustKey.ADDRESS_INFO, CustKey.ADDRESS_INFO,bean))
                finish()
            }else {
                var bundle =Bundle()
                bundle.putSerializable("addressBean",bean)
                startActivity(EditAddressActivity().javaClass,bundle)
            }



        }
        addressManageAdapter.setOnFastChildClickListener { view, position ->
            when (view.id) {
                R.id.llBtnUpdate -> {
                    val bean = addressManageAdapter.data[position]
                    var bundle =Bundle()
                    bundle.putSerializable("addressBean",bean)
                    startActivity(EditAddressActivity().javaClass,bundle)
                }
                R.id.llBtnDelete -> {
                    val id = addressManageAdapter.data[position].id
                    showCustomPopup(CenterSelectPopup(this, message = "确定删除地址吗?", sure = {
                        val map: HashMap<String, Any> = HashMap()
                        map["id"] = id
                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.deleteAddress(it1) }
                    }))
                }
                else -> {}
            }
        }
    }
    private fun initRefreshLayout() {
        binding.refreshLayout.setEnableLoadMore(false)
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
            }
        })
    }

    private fun getListData() {
        mViewModel.onAddressListMethod("")

    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@AddressActivity) {
                showToast(it)
            }
            againLoginMsg.observe(this@AddressActivity) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onAddressListData.observe(this@AddressActivity) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                addressManageAdapter.replaceData(it)
                if (it.isEmpty()){
                    addressManageAdapter.setEmptyView(notDataView!!)
                }
            }
            deleteAddressResult.observe(this@AddressActivity){
                showToast("删除成功")
                getListData()
            }
        }
    }


    inner  class AddressManageAdapter  : BaseQuickAdapter<AddressDetailBean, BaseViewHolder>(
        R.layout.layout_address_list_item) {

        override fun convert(helper: BaseViewHolder, item: AddressDetailBean) {
            helper.setText(R.id.tvName,item.name+"  "+item.mobile)
            helper.setText(R.id.tvDetailAddress,"${item.province}${if (item.city == item.province) "" else item.city}${item.area}${item.site}")
            helper.setVisible(R.id.tvDefault,item.ifdefault == 1)
        }
    }
}